<?php

namespace app\api\controller;

use app\api\model\SystemUser as SystemUserModel;
use app\common\model\Help;
use think\Controller;
use think\Db;
use think\Exception;
use think\facade\Validate;
use think\Request;

class SystemUser extends Controller
{
    /**
     * 获取管理员列表
     */
    public function getList()
    {
        try {
            $param = $this->request->get();
            if (!empty($param['params'])) {
                $params = $param['params'];
            } else {
                $params = [];
            }

            $help = new Help();
            $system_user = $help->system_user_find();


            // 分页参数
            $page = isset($params['pageNum']) ? intval($params['pageNum']) : 1;
            $limit = isset($params['pageSize']) ? intval($params['pageSize']) : 10;

            // 构建查询条件
            $model = new SystemUserModel();
            $query = $model->where('is_deleted', 0)->where("id!=10000");

            // 状态筛选
            if (isset($params['status']) && $params['status'] !== '') {
                $query->where('status', $params['status']);
            }

            // 角色筛选
            if (isset($params['role']) && $params['role'] !== '') {
                $query->where('role', $params['role']);
                if (isset($params['company']) && $params['company'] !== '') {
                    $company = $params['company'];
                    $select_company_id = Db::table("system_tenant")->where("company like '%$company%'")->column("system_user_id");
                    $query->where("id","in",$select_company_id);
                }

                if($params['role']=='tenant'){
                    if($system_user['role']!='superAdmin'){
                        $query->where("id","in",$system_user['id']);
                    }
                }
            }


            if (isset($params['identity']) && $params['identity'] !== '') {
                $query->where(['identity'=>$params['identity']]);
            }

            if (isset($params['organizationId']) && $params['organizationId'] !== '') {
                $organizationId_ids = $this->getAllChildrenIds($params['organizationId']);
                //$query->where(['organization_id'=>$params['organizationId']]);
                $query->where("organization_id","in",$organizationId_ids);
            }else{
                if (isset($params['identity']) && $params['identity'] == '成员') {
                    if($system_user['role']!='superAdmin'){
                        $organizationId_ids = Db::table("system_organization")->where(['system_user_id'=>$system_user['id']])->column("id");
                        $query->where("organization_id","in",$organizationId_ids);
                    }
                }
            }

            // 管理员名称模糊查询
            if (!empty($params['username'])) {
                $query->whereLike('username', '%' . $params['username'] . '%');
            }

            // 管理员昵称模糊查询
            if (!empty($params['truename'])) {
                $query->whereLike('truename', '%' . $params['truename'] . '%');
            }

            // 手机号模糊查询
            if (!empty($params['phone'])) {
                $query->whereLike('phone', '%' . $params['phone'] . '%');
            }

            // 微信昵称模糊查询
            if (!empty($params['weixin'])) {
                $query->whereLike('weixin', '%' . $params['weixin'] . '%');
            }

            // 排序 - 默认按创建时间降序
            $sortField = 'create_time';
            $sortOrder = 'desc';
            if (!empty($params['sortField'])) {
                $sortField = $params['sortField'];
                $sortOrder = $params['sortOrder'] ?? 'desc';
            }
            $query->order($sortField, $sortOrder);

            // 获取数据
            $list = $query->page($page, $limit)
                ->select();


            $total = $query->count();

            // 格式化数据
            $data = [];
            foreach ($list as $item) {
                $item['tenant'] = Db::table("system_tenant")->where(['system_user_id' => $item->id])->find();
                $data[] = [
                    'id' => $item->id,
                    'username' => $item->username,
                    'phone' => $item->phone,
                    'mail' => $item->mail,
                    'status' => (string)$item->status,
                    'desc' => $item->desc,
                    'truename' => $item->truename,
                    'avatar' => $item->avatar ?: '',
                    'weixin' => $item->weixin ?: '',
                    'sex' => (string)$item->sex,
                    'role' => $item->role,
                    'createTime' => $item->create_time,
                    'statusText' => $item->status_text,
                    'sexText' => $item->sex_text,
                    'roleText' => $item->role_text,
                    'tenant' => $item['tenant'],
                    'look'=>$item['pwd'],'organization_id'=>$item['organization_id']
                ];
            }

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => [
                    'list' => $data,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit
                ]
            ]);

        } catch (Exception $e) {
            return json([
                'code' => 500,
                'message' => '获取数据失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 获取所有下级组织ID（包括自身）
     */
    public function getAllChildrenIds($id)
    {
        $ids = [$id];
        $children = Db::table("system_organization")->where('pid', $id)->column('id');

        foreach ($children as $childId) {
            $ids = array_merge($ids, $this->getAllChildrenIds($childId));
        }

        return $ids;
    }

    /**
     * 新增管理员
     */
    public function add()
    {
        try {
            $params = $this->request->post();

            // 验证数据
            $model = new SystemUserModel();
            $result = $this->validate($params, $model->rules, $model->msg);
            if ($result !== true) {
                return json(['code' => 400, 'message' => $result]);
            }

            // 检查用户名是否重复
            $exists = SystemUserModel::where('username', $params['username'])
                ->where('is_deleted', 0)
                ->find();
            if ($exists) {
                return json(['code' => 400, 'message' => '管理员名称已存在']);
            }

            // 检查手机号是否重复
            if (!empty($params['phone'])) {
                $phoneExists = SystemUserModel::where('phone', $params['phone'])
                    ->where('is_deleted', 0)
                    ->find();
                if ($phoneExists) {
                    return json(['code' => 400, 'message' => '手机号已存在']);
                }
            }

            $help = new Help();
            $pwd = $params['password']??'';

            // 创建数据
            $data = [
                'username' => $params['username'],
                'password' => $params['password'],
                'truename' => $params['truename'],
                'phone' => $params['phone'] ?? '',
                'mail' => $params['mail'] ?? '',
                'status' => $params['status'],
                'desc' => $params['desc'] ?? '',
                'avatar' => $params['avatar'] ?? '',
                'weixin' => $params['weixin'] ?? '',
                'sex' => $params['sex'],
                'role' => $params['role'],
                'pwd' => $pwd,
                'p_id' => $help->system_user()
            ];

            $result = SystemUserModel::create($data);

            $insertId = Db::table("system_user")->where(["phone" => $params['phone'], 'username' => $params['username']])->value("id");
            $d['system_user_id'] = $insertId ?? '';
            $d["company"] = $params["company"] ?? '';
            $d["period"] = $params["period"] ?? '';
            $d["domain"] = $params["domain"] ?? '';
            $d["image"] = $params["image"] ?? '';

            if(!empty($params['role'])){
                if($params['role']=='tenant'){
                    $ishave = Db::table("system_tenant")->where(['system_user_id' => $insertId])->find();
                    if (empty($ishave)) {
                        Db::table("system_tenant")->insert($d);
                    }

                    $have = Db::table("system_organization")->where(['system_user_id' => $insertId])->find();
                    if (empty($have)) {
                        $dd['system_user_id'] = $insertId;
                        $dd['title'] = $params["company"]?? '';
                        $dd['create_time'] = time();
                        $dd['update_time'] = time();
                        $dd['remark'] = $params["company"]?? '';
                        $dd['curator'] = '空';
                        Db::table("system_organization")->insert($dd);
                    }
                }
            }

            $system_user = Db::table("system_user")->where(['id'=>$insertId])->find();

            $title = '';
            if(($system_user)&&($system_user['role']=='superAdmin')) {
                $title = "创建超级管理员";
                Db::table("system_user")->where(['id' => $insertId])->update(['identity'=>'超级管理员']);
            }

            if(($system_user)&&($system_user['role']=='tenant')) {
                $title = "创建租户";
                Db::table("system_user")->where(['id' => $insertId])->update(['identity'=>'租户']);
            }

            if(!empty($params['organization_id'])){
                $title = "创建成员";
                Db::table("system_user")->where(['id'=>$insertId])->update(['organization_id'=>$params['organization_id'],'identity'=>'成员']);
            }

            $help = new Help();
            $help->system_log($data, $title);

            if ($result) {
                return json([
                    'code' => 200,
                    'message' => '新增成功',
                    'data' => $result
                ]);
            } else {
                return json(['code' => 500, 'message' => '新增失败']);
            }

        } catch (Exception $e) {
            return json([
                'code' => 500,
                'message' => '新增失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 编辑管理员
     */
    public function update()
    {
        try {
            $params = $this->request->put();

            if (empty($params['id'])) {
                return json(['code' => 400, 'message' => 'ID不能为空']);
            }

            // 验证数据
            $model = new SystemUserModel();
            $rules = $model->rules;
            unset($rules['password']); // 编辑时密码不是必填

            $result = $this->validate($params, $rules, $model->msg);
            if ($result !== true) {
                return json(['code' => 400, 'message' => $result]);
            }

            // 检查记录是否存在
            $user = SystemUserModel::where('id', $params['id'])
                ->where('is_deleted', 0)
                ->find();
            if (!$user) {
                return json(['code' => 404, 'message' => '管理员不存在']);
            }

            // 检查用户名是否重复（排除自己）
            $usernameExists = SystemUserModel::where('username', $params['username'])
                ->where('id', '<>', $params['id'])
                ->where('is_deleted', 0)
                ->find();
            if ($usernameExists) {
                return json(['code' => 400, 'message' => '管理员名称已存在']);
            }

            // 检查手机号是否重复（排除自己）
            if (!empty($params['phone'])) {
                $phoneExists = SystemUserModel::where('phone', $params['phone'])
                    ->where('id', '<>', $params['id'])
                    ->where('is_deleted', 0)
                    ->find();
                if ($phoneExists) {
                    return json(['code' => 400, 'message' => '手机号已存在']);
                }
            }

            $pwd = $params['password']??'';

            // 更新数据
            $data = [
                'username' => $params['username'],
                'truename' => $params['truename'],
                'phone' => $params['phone'] ?? '',
                'mail' => $params['mail'] ?? '',
                'status' => $params['status'],
                'desc' => $params['desc'] ?? '',
                'avatar' => $params['avatar'] ?? '',
                'weixin' => $params['weixin'] ?? '',
                'sex' => $params['sex'],
                'role' => $params['role'],
                'pwd' => $pwd
            ];

            // 如果传了密码，则更新密码
            if (!empty($params['password'])) {
                $data['password'] = $params['password'];
            }

            $result = $user->save($data);

            $insertId = $params['id'];
            $d['system_user_id'] = $insertId ?? '';
            $d["company"] = $params["company"] ?? '';
            $d["period"] = $params["period"] ?? '';
            $d["domain"] = $params["domain"] ?? '';
            $d["image"] = $params["image"] ?? '';


            $system_user = Db::table("system_user")->where(['id'=>$insertId])->find();
            if(($system_user)&&($system_user['role']=='tenant')){
                $ishave = Db::table("system_tenant")->where(['system_user_id' => $insertId])->find();
                if (empty($ishave)) {
                    Db::table("system_tenant")->insert($d);
                } else {
                    Db::table("system_tenant")->where(['system_user_id' => $insertId])->update($d);
                }

                $have = Db::table("system_organization")->where(['system_user_id' => $insertId])->find();
                $dd['system_user_id'] = $insertId;
                $dd['title'] = $params["company"]?? '';
                $dd['create_time'] = time();
                $dd['update_time'] = time();
                $dd['remark'] = $params["company"]?? '';
                $dd['curator'] = '空';
                if (empty($have)) {
                    Db::table("system_organization")->insert($dd);
                }else{
                    Db::table("system_organization")->where(['system_user_id' => $insertId])->update($dd);
                }
            }


            $title = "";
            if(($system_user)&&($system_user['role']=='superAdmin')) {
                $title = '修改超级管理员';
                Db::table("system_user")->where(['id' => $insertId])->update(['identity'=>'超级管理员']);
            }

            if(($system_user)&&($system_user['role']=='tenant')) {
                $title = '修改租户';
                Db::table("system_user")->where(['id' => $insertId])->update(['identity'=>'租户']);
            }

            if(!empty($params['organization_id'])){
                $title = '修改成员';
                Db::table("system_user")->where(['id'=>$insertId])->update(['organization_id'=>$params['organization_id'],'identity'=>'成员']);
            }


            $help = new Help();
            $help->system_log($data, $title);


            if ($result !== false) {
                return json([
                    'code' => 200,
                    'message' => '更新成功'
                ]);
            } else {
                return json(['code' => 500, 'message' => '更新失败']);
            }

        } catch (Exception $e) {
            return json([
                'code' => 500,
                'message' => '更新失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 删除管理员
     */
    public function delete()
    {
        $id = input("id") ?? '';
        try {
            if (empty($id)) {
                return json(['code' => 400, 'message' => 'ID不能为空']);
            }

            $user = SystemUserModel::where('id', $id)
                ->where('is_deleted', 0)
                ->find();
            if (!$user) {
                return json(['code' => 404, 'message' => '管理员不存在']);
            }

            // 软删除
            $result = Db::table("system_user")->where('id', $id)->update(['delete_time' => time(), "is_deleted" => 1]);
            Db::table("system_tenant")->where('system_user_id', $id)->update(["is_deleted" => 1]);

            $help = new Help();
            $help->system_log($id, '删除管理员');

            if ($result) {
                return json([
                    'code' => 200,
                    'message' => '删除成功'
                ]);
            } else {
                return json(['code' => 500, 'message' => '删除失败']);
            }

        } catch (Exception $e) {
            return json([
                'code' => 500,
                'message' => '删除失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 检查用户名是否存在
     */
    public function checkUsername()
    {
        try {
            $username = $this->request->get('username');
            $id = $this->request->get('id');

            if (empty($username)) {
                return json(['code' => 400, 'message' => '用户名不能为空']);
            }

            $query = SystemUserModel::where('username', $username)
                ->where('is_deleted', 0);

            if (!empty($id)) {
                $query->where('id', '<>', $id);
            }

            $exists = $query->find();

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => [
                    'exists' => !empty($exists)
                ]
            ]);

        } catch (Exception $e) {
            return json([
                'code' => 500,
                'message' => '检查失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 检查手机号是否存在
     */
    public function checkPhone()
    {
        try {
            $phone = $this->request->get('phone');
            $id = $this->request->get('id');

            if (empty($phone)) {
                return json(['code' => 400, 'message' => '手机号不能为空']);
            }

            $query = SystemUserModel::where('phone', $phone)
                ->where('is_deleted', 0);

            if (!empty($id)) {
                $query->where('id', '<>', $id);
            }

            $exists = $query->find();

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => [
                    'exists' => !empty($exists)
                ]
            ]);

        } catch (Exception $e) {
            return json([
                'code' => 500,
                'message' => '检查失败: ' . $e->getMessage()
            ]);
        }
    }

    //个人详情
    public function info(){
        try {
            $help = new Help();
            $find = $help->system_user_find();
            $find['password'] = $find['pwd'];
            return json([
                'code' => 200,
                'message' => 'success',
                'data' => $find
            ]);
        } catch (Exception $e) {
            return json([
                'code' => 500,
                'message' => '检查失败: ' . $e->getMessage()
            ]);
        }
    }

    //修改个人中心
    public function editInfo(Request $request){
        try {
            $data = $request->param();
            Db::table("system_user")->where(['id'=>$data['id']])->update([
                'username'=>$data['username'],
                'password'=>md5($data['password']),
                'avatar'=>$data['avatar'],'file'=>$data['file'],'pwd'=>$data['password'],'company'=>$data['company']
            ]);

            $help = new Help();
            $help->system_log($data, '修改个人中心');

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => []
            ]);
        } catch (Exception $e) {
            return json([
                'code' => 500,
                'message' => '检查失败: ' . $e->getMessage()
            ]);
        }
    }

    //重置密码
    public function resetPassword(Request $request){
        try {
            $data = $request->param();
            Db::table("system_user")->where(['id'=>$data['id']])->update([
                'password'=>md5($data['password']),
                'pwd'=>$data['password']
            ]);

            $help = new Help();
            $help->system_log($data, '重置密码');

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => []
            ]);
        } catch (Exception $e) {
            return json([
                'code' => 500,
                'message' => '检查失败: ' . $e->getMessage()
            ]);
        }
    }

    //重置客户密码
    public function resetPassword2(Request $request){
        try {
            $data = $request->param();
            Db::table("store_customer")->where(['id'=>$data['id']])->update([
                'password'=>md5($data['password']),
                'pwd'=>$data['password']
            ]);

            $help = new Help();
            $help->system_log($data, '重置客户密码');

            return json([
                'code' => 200,
                'message' => 'success',
                'data' => []
            ]);
        } catch (Exception $e) {
            return json([
                'code' => 500,
                'message' => '检查失败: ' . $e->getMessage()
            ]);
        }
    }



}